//
//  HBDiscoverController.m
//  HeartBeat
//
//  Created by karong on 2023/8/23.
//

#import "HBDiscoverController.h"
#import "HBDiscoverCell.h"
#import "HBChannelModel.h"
#import "HBHistoryModel.h"
@interface HBDiscoverController ()
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (nonatomic, strong) NSArray * dataArray;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, assign) CGFloat contentHeight;
@property (nonatomic, strong) NSMutableDictionary *contentVCDict;
@property (weak, nonatomic) IBOutlet UIView *historyView;
@property (weak, nonatomic) IBOutlet UILabel *historyNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *historyLastReadLabel;
@property (weak, nonatomic) IBOutlet UIImageView *historyImageView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *historyBottom;
@property (nonatomic, strong) HBHistoryModel * history;
@property (nonatomic, strong) UIViewController * currentVC;
@end

@implementation HBDiscoverController
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.bg_gray_f2f2f2;
    [self loadDiscoverChannelRequest];
    [self loadHistoryReadRequest];
    [HBEvenManager event:@"Discovery_page" evenLogType:(HBEvenLogType_Show)];
}

- (void)viewLayout {
    [self.scrollView setContentSize:CGSizeMake(kScreenWidth * self.dataArray.count, self.contentHeight)];
}

- (void)turn2Male {
    for (HBChannelModel * channelModel in self.dataArray) {
        if (channelModel.channel_type == 1) {
            [self setContentVCWithIndex:[self.dataArray indexOfObject:channelModel]];
            return;
        }
    }
}

- (void)turn2Female {
    for (HBChannelModel * channelModel in self.dataArray) {
        if (channelModel.channel_type == 2) {
            [self setContentVCWithIndex:[self.dataArray indexOfObject:channelModel]];
            return;
        }
    }
}

- (void)loadHistoryReadRequest {
    if (appUserCenter.isLogin) {
        [HBRequest loadHistoryListWithPage:1 success:^(NSArray *array) {
            if (array.count > 0) {
                self.history = array.firstObject;
            }
        } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
            
        }];
    }
}

- (UIViewController *)customPageVCWithChannel:(HBChannelModel *)channel index:(NSInteger)index {
    UIViewController * target;
    if (channel.channel_type == 1 || channel.channel_type == 2) {
        target = [ViewManager channelVCWithChannel:channel];
        target.view.frame = CGRectMake(HBScreenWidth * index, 0, self.scrollView.bounds.size.width, self.contentHeight);
        [HBEvenManager event:@"Discovery_channel" evenLogType:(HBEvenLogType_Show) attributes:@{@"channel_id":SF(@"%ld", (long)channel.channel_type)}];
    }
    else {
        target = [ViewManager discoverItemVCWithChannel:channel];
        target.view.frame = CGRectMake(HBScreenWidth * index, 0, self.scrollView.bounds.size.width, self.contentHeight);
    }
    return target;
}

- (UIViewController *)channelPageVCWithChannel:(HBChannelModel *)channel index:(NSInteger)index {
    UIViewController * target = [ViewManager discoverItemVCWithChannel:channel];
    target.view.frame = CGRectMake(HBScreenWidth * index, 0, self.scrollView.bounds.size.width, self.contentHeight);
    return target;
}

// 获取並且添加子控制器
- (void)setContentVCWithIndex:(NSInteger)index {
    BOOL animated = YES;
    if(self.contentVCDict.count == 0) {
        animated = NO;
    }
    UIViewController *baseController = self.contentVCDict[@(index)];
    HBChannelModel * channelModel = self.dataArray[index];
    if(!baseController) {
        baseController = [self customPageVCWithChannel:channelModel index:index];
        baseController.view.frame = self.scrollView.bounds;
        baseController.view.mj_x = HBScreenWidth * index;
        baseController.view.mj_y = 0;
        [self.scrollView addSubview:baseController.view];
        [self addChildViewController:baseController];
        self.contentVCDict[@(index)] = baseController;
    }
    self.currentVC = baseController;
    [self.scrollView setContentOffset:CGPointMake(kScreenWidth * index, 0) animated:animated];
}

- (void)loadDiscoverChannelRequest {
    [HBRequest loadDiscoverChannelSuccess:^(NSArray *array) {
        self.dataArray = [[NSMutableArray alloc]initWithArray:array];
        [self viewLayout];
        if (self.dataArray.count > 0) {
            [self setContentVCWithIndex:self.selectIndex];
        }
        [self.listView reloadData];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (IBAction)taskAction:(id)sender {
    [ViewManager pushTaskVCInController:self];
}

- (IBAction)readAction:(id)sender {
    [ViewManager pushReadVCWithNovel_id:self.history.book_id chapter_id:self.history.chapter_id inController:self];
    self.history = nil;
}

- (IBAction)closeAction:(id)sender {
    self.history = nil;
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        CGFloat x = scrollView.contentOffset.x / HBScreenWidth;
        self.selectIndex = x;
        [self setContentVCWithIndex:self.selectIndex];
        [self.listView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:x inSection:0] atScrollPosition:(UICollectionViewScrollPositionCenteredHorizontally) animated:YES];
        [self.listView reloadData];
    }
}

#pragma mark UICollectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HBDiscoverCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HBDiscoverCell" forIndexPath:indexPath];
    [cell setDataWithObject:self.dataArray[indexPath.row] select:self.selectIndex == indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    HBChannelModel * channelModel = self.dataArray[indexPath.row];
    CGFloat width = [channelModel.title boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:indexPath.row == self.selectIndex ? 18 : 16 weight:(UIFontWeightMedium)]} context:nil].size.width;
    return CGSizeMake(width+20, 44);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.selectIndex = indexPath.row;
    [self setContentVCWithIndex:indexPath.row];
    [self.listView reloadData];
}

- (NSMutableDictionary *)contentVCDict {
    if (!_contentVCDict) {
        _contentVCDict = [[NSMutableDictionary alloc]init];
    }
    return _contentVCDict;
}

- (CGFloat)contentHeight {
    if (_contentHeight <= 0) {
        _contentHeight = HBScreenHeight - self.view.safeAreaInsets.top - 44 - self.tabBarController.tabBar.frame.size.height;
    }
    return _contentHeight;
}

- (void)setHistory:(HBHistoryModel *)history {
    _history = history;
    if (history) {
        self.historyBottom.constant = 0;
        [self.historyImageView sd_setImageWithURL:[NSURL URLWithString:self.history.thumb]];
        self.historyLastReadLabel.text = KEmptyStr(self.history.chapter_title);
        self.historyNameLabel.text = self.history.name;
    }
    else {
        self.historyBottom.constant = -120;
        [self.historyView removeFromSuperview];
    }
    [self.view uploadLayout];
}
@end
